(function(){
// csssprite 控制
var imgWrap = document.body.querySelector(".js-img-wrap"),     // 图片容器
    imgList = document.body.querySelector(".file-list"),    // 图片列表
    imgSelt = document.body.querySelector(".select-img");   // 选择图片的表单


// ----- 通过表单或拖动添加图片 -----
// 1、通过表单添加图片
document.getElementById("input-img").onchange = function(e){
    var pre_imgs_number = imgList.querySelectorAll(".file-li").length;
    readImg(this.files, 0, pre_imgs_number);
};

// 2、拖动图片添加
imgSelt.ondragenter = dragImg;
imgSelt.ondragover = dragImg;
imgSelt.ondrop = dragImg;

function dragImg(e){
    e.preventDefault();

    if(e.type == "drop"){
        var pre_imgs_number = imgList.querySelectorAll(".file-li").length;
        readImg(e.dataTransfer.files, 0, pre_imgs_number);
    }
}

// 为图片生成唯一识别的classname
function createCName(){
    if(!arguments.callee.count){
        arguments.callee.count = 100;
    }
    return "img" + arguments.callee.count++;
}

// 添加图片的核心函数
function readImg(files, i, pre_number){
    if(i == files.length) return;

    if(files[i].type.search(/image[\/]\w+/) >= 0){
        var reader = new FileReader();
        reader.onload = function(e){
            // 图片通过className = 图片名称 来识别
            var cName = createCName();

            // 添加图片到图片容器
            var img = new Image();
            img.src = reader.result;
            img.className = cName;
            var span = document.createElement("span");
            span.className = "img-ctn";
            span.appendChild(img);
            imgWrap.appendChild(span);
			
			// 当为拖动时, 图片加载是异步事件, 故需要延迟显示图片尺寸
			setTimeout(function(e){
                // 读取图片大小后, 重新设置span的宽高
                var newRule = setImgCtn(span, img);

				// 添加图片到文件列表
				var html = "";
				html += '<li class="file-li">';
				html += '<span class="btn-close js-del">&#x2573;</span>';
				html += '<span class="fileimg"><img src="'+ reader.result +'" class="thumbnail '+ cName +'"/></span> ';
				html += '<span class="filename">'+ files[i].name +'</span> ';
				html += '<span class="filesize">'+ img.width + "*"+ img.height +'</span> ';
				html += '<span class="imgpos"></span>';
                html += '<span class="ctnsize">'+ newRule[0] + "*"+ newRule[1] +'</span>';
				html += '<span class="filepos"></span>';
				html += '</li>';
				imgList.innerHTML += html;
			}, 1);

            // next
            readImg(files, i+1, pre_number);
        // img.parentNode 的位置
        };

        reader.readAsDataURL(files[i]);
    }
}

// 设置图片容器的尺寸
function setImgCtn(span, img){
    var newWidth = getNewSize(img.width),
        newHeight = getNewSize(img.height);

    // 容器的尺寸
    span.style.width    = newWidth + "px";
    span.style.height   = newHeight + "px";
    // 图片的位置: 上下左右居中(margin-top)
    img.style.marginTop = (newHeight - img.height)/2 + "px";
    
    return [newWidth, newHeight];
}

// 如果值<=20, 则返回20; 否则, 返回比值大, 且最接近的10的整数倍的数(30, 40, 50等)
function getNewSize(oldValue){
    return oldValue <= 20 ? 20 : Math.ceil(oldValue/10)*10;
}

// --------  图片列表区  -----------
document.body.querySelector(".js-file-list").onclick = function(e){
    var eTar = e.target;
    if(eTar.classList.contains("js-del")){
        var li = eTar.parentNode;
        // 从图片容器中删除图片: 图片的className = 图片的名称
        var cName = li.querySelector("img").className.split(" ")[1],
            img = imgWrap.querySelector("." + cName);
        imgWrap.removeChild(img.parentNode);

        // 从图片列表中删除图片
        li.parentNode.removeChild(li);
    }
};

// ---------   图片容器区  ---------------
// 图片容器中的图片可以被拖动 
// 用于交换拖动数据的全局变量:o: 源图片, s: 目标图片
// 将源图片放置在目标图片的前面
var wujiDrag = {o: null, s: null};      

imgWrap.ondragenter = drag;
imgWrap.ondragover = drag;
imgWrap.ondrop = drag;

function drag(e){
    e.preventDefault();

    if(e.type == "dragenter"){
        if(e.target.nodeName == "SPAN"){
            // cross anthor img
            wujiDrag.s = e.target;
        }
    }

    if(e.type == "drop"){
        if(wujiDrag.o){
            var target = (wujiDrag.s && wujiDrag.s != wujiDrag.o) ? wujiDrag.s : null;
            imgWrap.insertBefore(wujiDrag.o, target);
        }
        
    }
}

// 图片被拖动时，填充拖动数据
imgWrap.ondragstart = function(e){
    if(e.target.nodeName == "SPAN"){
        wujiDrag.o = e.target;
        wujiDrag.s = null;
    }
};

// ------ 生成图片按钮区 -------
// 生成图片的类型和质量选择
var createImgForm   = document.forms["create-img-form"],
    imgQualityWrap  = createImgForm.querySelector(".img-quality"),
    imgType         = createImgForm.elements["img-type"],
    imgQuality      = createImgForm.elements["img-quality"],
    imgQuaNum       = createImgForm.querySelector(".img-qua-num");
createImgForm.onchange = function(e){
    var eTar = e.target;

    if(eTar.name == "img-type"){
        // 选择图片类型
        if(eTar.value == "image/jpeg"){
            imgQualityWrap.style.display = "inline-block";
        }else{
            imgQualityWrap.style.display = "none";
        }
    }else if(eTar.name == "img-quality"){
        // 选择图片质量系数
        imgQuaNum.innerHTML = eTar.value;
    }
};

document.getElementById("create-img").onclick = function(){
    drawImg();
};


// 从图片容器生成合成图片
var canvas = document.getElementById("canvas-img");         // 画布
function drawImg(){
    // img-wrap的宽度和高度
    // 即：画布的尺寸
    var width       = parseInt(imgWrap.style.width),
        height      = parseInt(imgWrap.style.height);
    canvas.width    = width;
    canvas.height   = height;
    var cvsRect     = imgWrap.getBoundingClientRect();
    var ctx         = canvas.getContext("2d");
    /**
     * 因为画图时的左上角不包括边框, 故要从cvsRect中减去边框的宽度
     */

    // 清空画布
    ctx.clearRect(0, 0, width, height);

    // 载入图片
    // 图片位置: 图片距离wrap容器左上角的位置: offsetTop, offsetLeft
    // 图片的尺寸: 1、优先style.width 2、其次img.width, img.height
    var imgs = imgWrap.querySelectorAll("img"),
        i, item, len = imgs.length, cName = "",
        imgParent = null, relativeLi = null,
        imgParentLeft, imgParentTop, imgLeft, imgTop, imgWidth, imgHeight;
    for(i = 0; i < imgs.length; i++){
        item = imgs[i];

        // 图片
        cName           = item.className;               // className
        imgRect         = item.getBoundingClientRect();
        imgLeft         = imgRect.left - cvsRect.left -1;
        imgTop          = imgRect.top - cvsRect.top -1;
        imgWidth        = imgRect.width ? imgRect.width : (item.style.width ? parseInt(item.style.width) : item.width);
        imgHeight       = imgRect.height ? imgRect.height : (item.style.height ? parseInt(item.style.height) : item.height);

        // 外框元素
        imgParent       = item.parentNode;              
        imgParentRect   = imgParent.getBoundingClientRect();
        imgParentLeft   = imgParentRect.left - cvsRect.left - 1;
        imgParentTop    = imgParentRect.top - cvsRect.top - 1;

        // 画图
        ctx.drawImage(item, imgLeft, imgTop, imgWidth, imgHeight);

        // 标识位置
        relativeLi      = imgList.querySelector("." + cName).parentNode.parentNode;
        // 图片外框位置
        relativeLi.querySelector(".filepos").innerHTML = "background-position: "+ -imgParentLeft +"px "+ -imgParentTop +"px;";
        // 图片位置
        relativeLi.querySelector(".imgpos").innerHTML = "background-position: "+ -imgLeft +"px "+ -imgTop +"px;";
    }

    // 生成合成图片
    document.images["combine-img"].src = canvas.toDataURL(imgType.value, parseFloat(imgQuality.value));
} 

// 刷新, 离开时提现
window.onbeforeunload = function(e){
    return 1;
};

// ------- 改变图片容器的宽高背景 ----------
var btns_form = document.forms["btns-wrap"];
var img_ctn = document.querySelector(".js-img-wrap");

btns_form.onchange = function(e){
    var img_outer = document.querySelectorAll(".img-outer");

    var name = e.target.name,
        value = e.target.value;
    var attr_name = "",     // 属性名称
        attr_name1 = "",    // 属性css值
        attr_value = "",    // 属性js值
        elem = null;        // 要改变那个元素: img_ctn: 图片容器; img_outer: 图片的外层
    switch(name){
        case "ctn-width":
            attr_value = value + "px";
            attr_name = "width";
            elem = img_ctn;
            break;
        case "ctn-height":
            attr_value = value + "px";
            attr_name = "height";
            elem = img_ctn;
            break;
        case "ctn-bg":
            attr_value = value;
            attr_name = "background";
            elem = img_ctn;
            break;
        case "img-width":
            attr_value = value + "px";
            attr_name = "width";
            elem = img_outer;
            break;
        case "img-height":
            attr_value = value + "px";
            attr_name = "height";
            attr_name1 = "lineHeight";
            elem = img_outer;
            break;
        case "align":
            // 对齐方式
            attr_value = e.target.checked ? "center" : "left";
            attr_name  = "text-align";
            attr_name1 = "textAlign";
            elem       = img_ctn;
            break;
        default:
            break;
    }

    // 改变
    if(elem.length){
        for(var i = 0; i < elem.length; i++){
            elem[i].style[attr_name] = attr_value;
            if(attr_name1){
                elem[i].style[attr_name1] = attr_value;
            }
        }
    }else{
        elem.style[attr_name] = attr_value;
    }
};

// 页面加载时， 图片容器的高度和宽度与表单中的值相同
btns_form.onchange({target: btns_form.elements["ctn-width"]});
btns_form.onchange({target: btns_form.elements["ctn-height"]});



// 当图片容器改变大小时，回填数据到表单中
// 通过拖动事件来模拟 与css resize 同时的事件
var if_drag = false;        // 是否正在拖动

// 按下鼠标
img_ctn.addEventListener("mousedown", function(e){
    if_drag = true;    
}, false);
// 松开鼠标
    // img.parentNode 的位置
img_ctn.addEventListener("mouseup", function(e){
    if_drag = false;    
}, false);

// mousemove
img_ctn.addEventListener("mousemove", function(e){
    if(if_drag){
        var ctn_width = this.clientWidth,
            ctn_height = this.clientHeight;

        btns_form.elements["ctn-width"].value = ctn_width;
        btns_form.elements["ctn-height"].value = ctn_height;
    }
}, false);

})();
